// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({env: cloud.DYNAMIC_CURRENT_ENV});
const db = cloud.database();
const CustomError = require("./CustomError");
// 云函数入口函数
exports.main = async (event = {}, context) => {
    switch (event.actionName) {
        case "addRecord": //增加寻丢记录
            return await addRecord(event);
        case "addFoundRecord": //增加还拾记录
            return await addFoundRecord(event);
        case "getRecordList": //获取记录列表
            return await getRecordList(event);
        case "getRecordDetail": //获取记录详情
            return await getRecordDetail(event);
        case "getRecordCount": //获取记录个数
            return await getRecordCount(event);
        case "deleteRecord": //删除记录
            return await deleteRecord(event);
        case "updateRecord": //更新记录
            return await updateRecord(event);
    }
}

/*
* 获取所有文本信息
* */
function getContentToText(data) {
    let content = "";
    for (let i in data) {
        if (i !== "images") {
            content += data[i] + ","
        }
    }
    return content
}

/*
* 增加记录
* */
async function addRecord(event) {
    try {
        let {params} = event;
        if (Object.keys(params).length === 0) {throw new Error("参数为空")}
        let {OPENID} = cloud.getWXContext();
        let content = getContentToText(params);
        await cloud.openapi.security.msgSecCheck({content: content})
        let res = await db.collection("record").add({
            data: Object.assign(params, {
                type: params.type || "lost",  //类型  lost/found
                complete: 0, //0 完成状态  /未完成 1已完成
                verify: 0, //审核状态  /0审核中 1已通过 2未通过
                openId: OPENID,
                views: 0, //浏览次数
                shares: 0, //分享次数
                createTime: new Date().getTime(),
            })
        })
        return {
            data: {_id: res._id},
            status: 0
        };
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
*
* 增加还拾记录
* */
async function addFoundRecord(event) {
    try {
        let {params} = event;
        if (Object.keys(params).length === 0) {throw new Error("参数为空")};
        let {OPENID} = cloud.getWXContext();
        let content = getContentToText(params);
        await cloud.openapi.security.msgSecCheck({content: content})
        let res = await db.collection("record").add({
            data: Object.assign(params, {
                type: "found", //类型  lost/found
                complete: 0, //0 完成状态  /未完成 1已完成
                verify: 0, //审核状态  /0审核中 1已通过 2未通过
                openId: OPENID,
                views: 0, //浏览次数
                shares: 0, //分享次数
                createTime: new Date().getTime(),
            })
        })
        return {
            data: {_id: res._id},
            status: 0
        };
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }

}

/*
* 查询记录
* */
async function getRecordList(event) {
    try {
        const _ = db.command;
        let {params} = event;
        let {OPENID} = cloud.getWXContext();
        let page = params.page - 1 || 0;
        let pageSize = params.pageSize || 20; //分页限制， 每页20
        let newData = {}, verify;
        params.personal ? newData.openId = OPENID : null;
        params.complete || params.complete === 0 ? newData.complete = params.complete : null;
        params.type ? newData.type = params.type : null
        verify = (function (value) { //支持[x,x,x] 和 "x,x,x"格式的参数
            if (value || value === 0) {
                return Array.isArray(value) ? (value.length > 0 ? value : false) : value.toString().split(",").map(function (item) {
                    return parseInt(item || 0)
                })
            } else {
                return false
            }
        })(params.verify)
        verify ? newData.verify = _.in(verify) : null;
        params.createTime ? newData.createTime = _.gte(params.createTime) : null
        params.region ? newData.region = new db.RegExp({
            regexp: params.region,
        }): null;
        const collection = await db.collection("record").where(newData);
        const countResult = await collection.count(); //获取总数
        const total = countResult.total;
        let res = await collection
            .orderBy("createTime", "desc")
            .skip(page * pageSize)
            .limit(pageSize)
            .get()
        return {
            data: {
                list: res.data,
                page: params.page,
                pageSize: pageSize,
                total: total,
            },
            status: 0
        }
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }

}

/*
* 查看记录详情
* */
async function getRecordDetail(event) {
    try {
        let {id} = event.params;
        if (!id) {throw new Error("参数为空")}
        let res =  await db.collection("record").doc(id).get();
        return {
            data: res.data,
            status: 0
        };
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 删除记录
* */
async function deleteRecord(event) {
    try {
        let {id} = event.params;
        if (!id) {throw new Error("参数为空")}
        let content = await db.collection("record").doc(id);
        let res = await content.get();
        if (res.data.images.length > 0) {
            await cloud.deleteFile({fileList: res.data.images})
        }
        await content.remove();
        return {
            data: content.data,
            status: 0,
        };
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 编辑
* */
async function updateRecord(event) {
    try {
        let {id, ...data} = event.params;
        if (!id) {throw new Error("参数为空")}
        let res =  await db.collection("record").doc(id).update({
            data: Object.assign(data, {
                updateTime: new Date().getTime()
            })
        });
        return {
            data: {_id: res._id},
            status: 0
        };
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 获取记录数量
* */
async function getRecordCount(event) {
    try {
        let {OPENID} = cloud.getWXContext();
        const collection = await db.collection("record");
        const lostResult = await collection.where({type: "lost", openId: OPENID}).count(); //获取总数
        const foundResult = await collection.where({type: "found", openId: OPENID}).count(); //获取总数
        return {
            data: {
                lostTotal: lostResult.total,
                foundTotal: foundResult.total
            },
            status: 0,
        }
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}